package com.ruoyi.web.controller.bbsAdmin;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.bbsAdmin.domain.LoginStatistics;
import com.ruoyi.bbsAdmin.mapper.LoginRecordMapper;
import com.ruoyi.bbsAdmin.mapper.LoginStatisticsMapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.bbsAdmin.domain.LoginRecord;
import com.ruoyi.bbsAdmin.service.ILoginRecordService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 论坛用户登陆记录Controller
 * 
 * @author ruoyi
 * @date 2024-04-23
 */
@RestController
@RequestMapping("/bbs_login_record/loginRecord")
public class LoginRecordController extends BaseController
{
    @Autowired
    private ILoginRecordService loginRecordService;

    @Resource
    LoginRecordMapper loginRecordMapper;

    @Resource
    LoginStatisticsMapper loginStatisticsMapper;

    /**
     * 查询论坛用户登陆记录列表
     */
    @PreAuthorize("@ss.hasPermi('bbsAdmin:loginRecord:list')")
    @GetMapping("/list")
    public TableDataInfo list(LoginRecord loginRecord)
    {
        startPage();
        List<LoginRecord> list = loginRecordService.selectLoginRecordList(loginRecord);
        return getDataTable(list);
    }

    /**
     * 导出论坛用户登陆记录列表
     */
    @PreAuthorize("@ss.hasPermi('bbsAdmin:loginRecord:export')")
    @Log(title = "论坛用户登陆记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, LoginRecord loginRecord)
    {
        List<LoginRecord> list = loginRecordService.selectLoginRecordList(loginRecord);
        ExcelUtil<LoginRecord> util = new ExcelUtil<LoginRecord>(LoginRecord.class);
        util.exportExcel(response, list, "论坛用户登陆记录数据");
    }

    /**
     * 获取论坛用户登陆记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('bbsAdmin:loginRecord:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return AjaxResult.success(loginRecordService.selectLoginRecordById(id));
    }

    /**
     * 新增论坛用户登陆记录
     */
    @PreAuthorize("@ss.hasPermi('bbsAdmin:loginRecord:add')")
    @Log(title = "论坛用户登陆记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LoginRecord loginRecord)
    {
        return toAjax(loginRecordService.insertLoginRecord(loginRecord));
    }

    /**
     * 修改论坛用户登陆记录
     */
    @PreAuthorize("@ss.hasPermi('bbsAdmin:loginRecord:edit')")
    @Log(title = "论坛用户登陆记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody LoginRecord loginRecord)
    {
        return toAjax(loginRecordService.updateLoginRecord(loginRecord));
    }

    /**
     * 删除论坛用户登陆记录
     */
    @PreAuthorize("@ss.hasPermi('bbsAdmin:loginRecord:remove')")
    @Log(title = "论坛用户登陆记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(loginRecordService.deleteLoginRecordByIds(ids));
    }


    @GetMapping("/gerUserCount")
    public AjaxResult getUserCount(int schoolId)
    {
        Date date =new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate2 = sdf.format(date);
        QueryWrapper<LoginStatistics> statisticsQueryWrapper =new QueryWrapper<>();
        statisticsQueryWrapper.eq("login_date",formattedDate2)
                .eq("school_id",schoolId);
        List<LoginStatistics> statisticsList = loginStatisticsMapper.selectList(statisticsQueryWrapper);
        LoginStatistics loginStatistics =new LoginStatistics();
        Map<String, Object> data = new HashMap<>();
        //更新
        if (statisticsList!=null && statisticsList.size()>0){
            loginStatistics=statisticsList.get(0);
            data.put("userCount", loginStatistics.getUserCount());
            data.put("loginCount", loginStatistics.getLoginCount());
        }
        else{
            data.put("userCount", 0);
            data.put("loginCount", 0);
        }
        return AjaxResult.success(data);


    }

    @PreAuthorize("@ss.hasAnyRoles('xygly,admin')")
    @GetMapping("/gerAllSchoolUserCount")
    public AjaxResult gerAllSchoolUserCount(String schoolIdStr)
    {
        //今日访问人数
        Map sqlRes = loginStatisticsMapper.getTotalCountsBySchoolIds(schoolIdStr);

        Map<String, Object> data = new HashMap<>();
        data.put("userCount", sqlRes.get("total_user_count"));
        data.put("loginCount", sqlRes.get("total_login_count"));
        return AjaxResult.success(data);
    }

    @GetMapping("/gerUserCountByTimeGroup")
    public AjaxResult getUserCountByTimeGroup(int schoolId,int intervalMinutes)
    {
        List<Map<String, Object>> userCount = new ArrayList<>();
        List<Map<String, Object>> loginCount = new ArrayList<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //今日访问人数
        List<Map<String, Object>> sqlRes = loginStatisticsMapper.getDailyCountsBySchoolId(schoolId);
        for (Map<String, Object> dailyCount : sqlRes) {
            Date loginDateRaw = (Date) dailyCount.get("login_date");
            String loginDate = dateFormat.format(loginDateRaw);
            // 转换数据类型
            Long totalUserCount = ((Number) dailyCount.get("total_user_count")).longValue();
            Long totalLoginCount = ((Number) dailyCount.get("total_login_count")).longValue();

            Map<String, Object> userCountMap = new HashMap<>();
            userCountMap.put("time_group", loginDate);
            userCountMap.put("user_login_count", totalUserCount);
            userCount.add(userCountMap);

            Map<String, Object> loginCountMap = new HashMap<>();
            loginCountMap.put("time_group", loginDate);
            loginCountMap.put("login_count", totalLoginCount);
            loginCount.add(loginCountMap);
        }
        Map<String, Object> data = new HashMap<>();
        data.put("userCount", userCount);
        data.put("loginCount", loginCount);
        return AjaxResult.success(data);
    }

    @PreAuthorize("@ss.hasAnyRoles('xygly,admin')")
    @GetMapping("/gerAllSchoolUserCountByTimeGroup")
    public AjaxResult gerAllSchoolUserCountByTimeGroup(String schoolIdStr,int intervalMinutes)
    {
        List<Map<String, Object>> userCount = new ArrayList<>();
        List<Map<String, Object>> loginCount = new ArrayList<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //今日访问人数
        List<Map<String, Object>> sqlRes = loginStatisticsMapper.getDailyCountsBySchoolIds(schoolIdStr);
        for (Map<String, Object> dailyCount : sqlRes) {
            Date loginDateRaw = (Date) dailyCount.get("login_date");
            String loginDate = dateFormat.format(loginDateRaw);
            // 转换数据类型
            Long totalUserCount = ((Number) dailyCount.get("total_user_count")).longValue();
            Long totalLoginCount = ((Number) dailyCount.get("total_login_count")).longValue();

            Map<String, Object> userCountMap = new HashMap<>();
            userCountMap.put("time_group", loginDate);
            userCountMap.put("user_login_count", totalUserCount);
            userCount.add(userCountMap);

            Map<String, Object> loginCountMap = new HashMap<>();
            loginCountMap.put("time_group", loginDate);
            loginCountMap.put("login_count", totalLoginCount);
            loginCount.add(loginCountMap);
        }
        Map<String, Object> data = new HashMap<>();
        data.put("userCount", userCount);
        data.put("loginCount", loginCount);
        return AjaxResult.success(data);
    }
}
